package com.miniapp.controller;

import com.miniapp.dto.SysLoginDTO;
import com.miniapp.dto.form.PasswordDTO;
import com.miniapp.entity.MiniUserEntity;
import com.miniapp.entity.MiniUserLoginLogEntity;
import com.miniapp.entity.enums.UserStatus;
import com.miniapp.entity.enums.UserType;
import com.miniapp.service.*;
import com.miniapp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author linyuchi
 * @date 2016年11月10日 下午1:15:31
 */
@Api(value = "登陆API",description = "登陆")
@RestController
public class MiniLoginController extends AbstractController {
	@Autowired
	private MiniUserService miniUserService;
	@Autowired
	private MiniUserTokenService miniUserTokenService;
	@Autowired
	private MiniCaptchaService miniCaptchaService;
	@Autowired
	private MiniUserLoginLogService miniUserLoginLogService;
	@Autowired
	private SmsService smsService;
	public static final String REGISTER_MOBILE="REGISTER_MOBILE";
	/**
	 * 验证码
	 */
	@ApiOperation(value="获取验证码", notes="获取验证码")
	@ApiImplicitParam(name = "uuid", value = "uuid",paramType = "query", required = true, dataType = "String")
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, @RequestParam(value = "uuid", required = true) String uuid )throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = miniCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	@ApiOperation(value="登陆", notes="登陆")
	public Map<String, Object> login(@RequestBody @ApiParam(name="SysLogin",value="登陆信息",required=true) SysLoginDTO form)throws IOException {
		boolean captcha = miniCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
		MiniUserEntity user = miniUserService.findByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus().equals(UserStatus.UNACTIVE)){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = miniUserTokenService.createToken(user.getId());

		//记录登陆信息到数据库
		//获取request
		HttpServletRequest request = RequestHelper.getCurrentRequest();
		//设置IP地址
		MiniUserLoginLogEntity miniUserLoginLog = new MiniUserLoginLogEntity();
		miniUserLoginLog.setLoginIp(RequestHelper.getRemoteHost(request));
		miniUserLoginLog.setUserId(user.getId());
		miniUserLoginLogService.saveOrUpdate(miniUserLoginLog);

		Map map = new HashMap();
		map.put("name",user.getName());
		map.put("id",user.getId());
		map.put("mobile",user.getMobile());
		map.put("userType",user.getUserType());

		r.put("user",map);
		return r;
	}
	/**
	 * 生成验证码返回手机
	 */
	@GetMapping("/sys/create_vcode")
	@ResponseBody
	public R createVcode(HttpServletRequest request) {
		String mobile = request.getParameter("mobile");
		String vcode = BaseUtils.createRandomString(6);
		if (this.miniUserService.isMobileExist(mobile)) {
			return  R.error("该手机号码已经注册过");
		}
		Boolean isSend = smsService.sendVerificationCode(RequestHelper.getRemoteHost(request), mobile, vcode);
		if (!isSend) {
			return  R.error("短信发送失败");
		}
		JedisUtils.set(REGISTER_MOBILE+mobile,vcode,60);
		logger.info("key:" + REGISTER_MOBILE+mobile);

		return  R.ok("短信发送成功");
	}

	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
    @ApiOperation(value="退出", notes="退出")
	public R logout() {
		miniUserTokenService.logout(getUserId());
		return R.ok();
	}

	/**
	 * 注册
	 */
	@PostMapping("/sys/register")
	@ApiOperation(value="用户注册", notes="用户注册")
	public R regist(@RequestBody @ApiParam(name="SysRegister",value="用户注册",required=true) PasswordDTO form) throws IOException  {

		String captcha = form.getCaptcha();
		String jedisKey = REGISTER_MOBILE + form.getMobile();
		if (captcha.equals(JedisUtils.get(jedisKey))){
			MiniUserEntity miniUser = new MiniUserEntity();
			miniUser.setUsername(form.getMobile());
			miniUser.setName(form.getMobile());
			miniUser.setMobile(form.getMobile());
			miniUser.setPassword(form.getPassword());
//			MiniUserEntity pUser = miniUserService.findAgenceUser(form.getHost());
//			if (BaseUtils.isEmpty(pUser)){
//				return R.error("获取用户代理异常!");
//			}
			miniUser.setUserType(UserType.COMMON.getValue());
			miniUser.setParentUserId(1L);
			miniUserService.saveUser(miniUser);
			//删除验证码
			JedisUtils.del(jedisKey);
		} else {
			return R.error("验证码过期,请重新获取验证码!");
		}
		return R.ok();
	}


}
